import { Button, Space, Table, Modal, Form, Input } from 'antd';
import axios from 'axios';
import React, { useEffect, useState } from 'react';

axios.defaults.baseURL = '/manage'

interface ListItem {
  id: string
  name: string
  tel: string
}

const App = () => {
  const [list, setList] = useState<ListItem[]>([]);
  const [open, setOpen] = useState(false)
  const [form] = Form.useForm();
  const [searchValue, setSearchValue] = useState("")
  const fetchList = async () => {
    const resp = await axios.get('/list', { params: { q: searchValue } });
    setList(resp.data)
  }
  useEffect(() => {
    fetchList()
  }, [searchValue]);

  const handleDelete = async (id: string) => {
    await axios.delete('/list/' + id);
    await fetchList()
  }
  const handleEdit = (row: ListItem) => {
    setOpen(true);
    form.setFieldsValue(row)
  }
  const handleAdd = () => {
    setOpen(true)
    form.resetFields()
  }
  const handleOK = async () => {
    const data = form.getFieldsValue();
    if(data.id) {
      // 编辑
      await axios.put('/list/' + data.id, data)
    } else {
      await axios.post('/list', data)
    }
    setOpen(false);
    fetchList()
  }
  const columns = [{
    key: '1',
    title: 'id',
    dataIndex: "id"
  }, {
    key: '2',
    title: '姓名',
    dataIndex: 'name'
  }, {
    key: '3',
    title: '电话',
    dataIndex: 'tel'
  }, {
    key: '1',
    title: '操作',
    render(row: ListItem) {
      return (
        <Space>
          <Button type="primary" onClick={() => handleEdit(row)}>编辑</Button>
          <Button type="primary" danger onClick={() => handleDelete(row.id)}>删除</Button>
        </Space>
      )
    }
  }]

  return (
    <div>
      <Input value={searchValue} onChange={e => setSearchValue(e.target.value as string)}></Input>
      <Button type="primary" onClick={() => handleAdd()}>添加</Button>
      <Table dataSource={list} columns={columns}></Table>
      <Modal title="添加/编辑" open={open} onCancel={() => setOpen(false)} onOk={() => handleOK()}>
        <Form form={form}>
          <Form.Item style={{ display: 'none' }} name="id">
            <Input placeholder='请输入姓名'></Input>
          </Form.Item>
          <Form.Item name="name">
            <Input placeholder='请输入姓名'></Input>
          </Form.Item>
          <Form.Item name="tel">
            <Input placeholder='请输入手机号'></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )

}

export default App